package bb.lanxing.activity.sport;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.github.mikephil.charting.utils.Utils;

import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.databinding.unit.UnitConstants;
import bb.lanxing.lib.kt.model.geo.GeoBounds;
import bb.lanxing.lib.kt.model.geo.IGeoPoint;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.mvp.presetner.WorkoutMergePreviewPresenterImpl;
import bb.lanxing.mvp.presetner.i.IWorkoutMergePreviewPresenter;
import bb.lanxing.mvp.view.IWorkoutMergePreviewView;
import bb.lanxing.service.SyncTaskService;
import bb.lanxing.util.BiCiCoorConverter;
import bb.lanxing.util.MapUtil;
import bb.lanxing.util.map.GeoCoorConverter;
import bb.lanxing.util.map.MapConfigs;
import bb.lanxing.util.ui.DrawableUtils;

import java.util.ArrayList;
import java.util.List;

public class WorkoutMergePreviewActivity extends BaseActivity implements IWorkoutMergePreviewView, View.OnClickListener {
    protected static final int[] colors = {0xaa7b1fa2, 0xaae51c23, 0xaa3b50ce, 0xaa00796b, 0xaae64a19};//from array: lushu_colors

    private TextureMapView mTextureMapView;
    private BaiduMap mBaiduMap;
    private bb.lanxing.utils.MapUtil mapUtil;

    private LatLng mCurrentLatLng;

    private TextView mergeConfirm;
    private IWorkoutMergePreviewPresenter mergePreviewPresenter;
    private List<Workout> workouts;

    private boolean isMerging = false;
    private float maxZoomLevel = 17.0f;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workout_merge_preview);
        bindView(getWindow().getDecorView());
        setupActionBar(true);

        mergePreviewPresenter = new WorkoutMergePreviewPresenterImpl(this);
        IGeoPoint earth2Common = GeoCoorConverter.earth2Common(MapConfigs.getNotNullLastIGeoLocation());
        mCurrentLatLng = BiCiCoorConverter.earth2Baidu(new LatLng(earth2Common.getLatitude(), earth2Common.getLongitude()));
        mTextureMapView.getMap();
        mBaiduMap = mTextureMapView.getMap();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(maxZoomLevel).target(mCurrentLatLng).build()));
        mapUtil = bb.lanxing.utils.MapUtil.getInstance();
        mapUtil.init(mTextureMapView);
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        long[] longArrayExtra = getIntent().getLongArrayExtra("workout_id_arrays");
        Long[] lArr = new Long[longArrayExtra.length];
        for (int i = 0; i < longArrayExtra.length; i++) {
            lArr[i] = longArrayExtra[i];
        }
        mergePreviewPresenter.loadWorkout(lArr);
        if (mergePreviewPresenter.checkPermission()) {
            return;
        }
        mergeConfirm.setText(R.string.workout_merge_no_permission);
        mergeConfirm.setEnabled(false);
    }

    @Override
    public void onWorkoutLoaded(final List<Workout> vWorkouts) {
        if (vWorkouts == null || vWorkouts.isEmpty()) {
            return;
        }
        workouts = vWorkouts;
        double d = Utils.DOUBLE_EPSILON;
        for (Workout workout : workouts) {
            d += workout.getDistance();
        }
        String formattedString = getString(R.string.workout_merge_btn, String.format("%.1f", (d / 1000.0d)) + UnitConstants.UNIT_SIZE_KM);
        mergeConfirm.setText(formattedString);
        drawSegmentWorkout(workouts);
    }

    @Override
    public void onStartMerge() {
        isMerging = true;
        mergeConfirm.setEnabled(false);
        toast(R.string.workout_merge_started);
    }

    @Override
    public void onMergeProgress(final int index, final int count) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mergeConfirm.setText(getString(R.string.workout_merge_progressing, index + 1, count));
            }
        });
    }

    @Override
    public void onMergeFinished(Workout vWorkout) {
        toast(R.string.workout_merge_succeed);
        Intent intent = new Intent(this, SyncTaskService.class);
        intent.putExtra(SyncTaskService.EXTRA_TASK_ID, 1);
        intent.putExtra("workout_id", vWorkout.getId());
        intent.putExtra(SyncTaskService.EXTRA_ONLY_WIFI, SharedManager.getInstance().getAutoUploadMode() == 2);
        startService(intent);
        Intent intent1 = new Intent(this, SportRecordDetailActivity.class);
        intent1.putExtra("workoutId", vWorkout.getId());
        startActivity(intent1);
        Intent intent2 = new Intent();
        intent2.putExtra("workout", (Parcelable) vWorkout);
        setResult(-1, intent2);
        finish();
    }

    public void drawSegmentWorkout(List<Workout> vWorkouts) {
        View view;
        int i;
        TextView textView;
        View inflate = LayoutInflater.from(this).inflate(R.layout.map_marker_merge_workout_info, (ViewGroup) null);
        TextView textView2 = inflate.findViewById(R.id.merge_workout_index);
        TextView textView3 = inflate.findViewById(R.id.merge_workout_title);
        GeoBounds.Builder builder = new GeoBounds.Builder();
        int i2 = 0;
        while (i2 < vWorkouts.size()) {
            Workout workout = vWorkouts.get(i2);
            List<Trackpoint> trackPoints = workout.getTrackPoints();
            ArrayList<LatLng> arrayList = new ArrayList(trackPoints.size());
            for (Trackpoint trackpoint : trackPoints) {
                arrayList.add(BiCiCoorConverter.earth2Baidu(new LatLng(trackpoint.getLatitude(), trackpoint.getLongitude())));
                builder.include(trackpoint.getLatitude(), trackpoint.getLongitude());
            }
            int i3 = i2;
            if (arrayList.isEmpty()) {
                view = inflate;
                textView = textView2;
                i = i3;
            } else {
                int i4 = colors[Math.min(i3, 4)];
                drawWorkout(i4, arrayList);
                textView2.setText(String.valueOf(i3 + 1));
                textView3.setText(workout.getTitle());
                DrawableUtils.setBackgroundTint(inflate, i4);
                DrawableUtils.setBackgroundTint(textView2, i4);
                Drawable convertView = MapUtil.convertView(inflate);
                float intrinsicHeight = (convertView.getIntrinsicHeight() / 2.0f) / convertView.getIntrinsicWidth();
                LatLng latLng = arrayList.get(0);
                view = inflate;
                i = i3;
                if (i == vWorkouts.size() - 1) {
                    LatLng latLngEnd = arrayList.get(arrayList.size() - 1);
                    textView = textView2;
                } else {
                    textView = textView2;
                }
            }
            inflate = view;
            textView2 = textView;
            i2 = i + 1;
        }
    }

    private void drawWorkout(int color, List<LatLng> points) {
        if (points == null) {
            return;
        }
        mapUtil.drawPolyline(color, points);
    }

    private void mergeWorkout() {
        List<Workout> list = workouts;
        if (list != null) {
            mergePreviewPresenter.mergeWorkout(list);
        }
    }

    @Override
    public void onBackPressed() {
        if (cancelMerge()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onHomeBack() {
        return cancelMerge();
    }

    private boolean cancelMerge() {
        if (isMerging) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.workout_merge_cancel_title)
                    .setMessage(R.string.workout_merge_cancel_msg)
                    .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        dialog.dismiss();
                        mergePreviewPresenter.cancelMerge();
                        isMerging = false;
                    }).show();
            return true;
        }
        return false;
    }

    @Override
    public void onMergeCanceled() {
        finish();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.mapChangeBtn) {
        } else if (id == R.id.workout_merge_confirm) {
            mergeWorkout();
        }
    }

    private void bindView(View bindSource) {
        mTextureMapView = bindSource.findViewById(R.id.textureMapView);
        mergeConfirm = bindSource.findViewById(R.id.workout_merge_confirm);
    }
}